﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class CircleGuide : GuideBase
{
    private float _r;

    private Transform _guide;
    private TextMeshProUGUI _text;

    private Canvas _canvas;
    private RectTransform _target;

    public void Init(int index, Canvas canvas, RectTransform target, Action<int> doneAction)
    {
        _index = index;
        _canvas = canvas;
        _target = target;
        _doneAction = doneAction;
    }

    public void Show(string guide)
    {
        Guide(_canvas, _target, Screen.width, 1.1f, 0.2f);

        _text.text = $"{guide}";
    }

    public override void Guide(Canvas canvas, RectTransform target)
    {
        base.Guide(canvas, target);

        _guide = transform.Find("Guide");
        _text = transform.Find("Guide/Text").GetComponent<TextMeshProUGUI>();

        var width = (_targetCorners[3].x - _targetCorners[0].x) / 2;
        var height = (_targetCorners[1].y - _targetCorners[0].y) / 2;

        //计算半径
        _r = Mathf.Sqrt(width * width + height * height);

        _material.SetFloat("_Slider", _r);

        //设置文本位置
        RectTransform parentRect = _guide.GetComponent<RectTransform>();

        Vector2 pivot = new Vector2();
        pivot.x = target.localPosition.x > 0 ? 1 : 0;
        pivot.y = target.localPosition.y > 0 ? 1 : 0;
        float x = target.localPosition.x > 0 ? -target.rect.width / 2 - 40 : target.rect.width / 2 + 40;
        float y = target.localPosition.y > 0 ? target.rect.height / 2 : -target.rect.height / 2;
        parentRect.pivot = pivot;
        parentRect.localPosition = new Vector3(target.localPosition.x + x, target.localPosition.y + y, 0);
    }

    public void Guide(Canvas canvas, RectTransform target, float startSize, float scale, float time)
    {
        Guide(canvas, target);

        DOTween.To(() => startSize, (value) => startSize = value, _r * scale, time)
            .SetEase(Ease.Flash)
            .OnUpdate(() => { _material.SetFloat("_Slider", startSize); })
            .OnComplete(() => { });
    }

    public override void OnMaskButtonClick()
    {
        base.OnMaskButtonClick();
        _doneAction?.Invoke(_index);
    }
}